/**
 * 
 */
package com.pmantra.mashapp.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.pmantra.mashapp.domain.Role;
import com.pmantra.mashapp.domain.User;
import com.pmantra.mashapp.dto.UserListDto;
import com.pmantra.mashapp.service.UserService;

/**
 * @author pmantravadi
 *
 */

@Controller
@RequestMapping(value="/create")
public class UserController {
	
	@Autowired
	private UserService service;
	
	@RequestMapping(method=RequestMethod.POST)
	public String createContact(User user, BindingResult result){
		Role dummyRole = new Role();
		user.setRole(dummyRole);
		service.create(user);
		return "redirect:/create";
	}
	
	@RequestMapping(value="/records")
	public @ResponseBody UserListDto getUsers(){
		UserListDto userListDto = new UserListDto();
		userListDto.setUsers(service.readAll());
		return userListDto;
	}
	
	@RequestMapping(method=RequestMethod.GET)
	public String getCreateForm() {
		System.out.println("get called");
		List<User> readAll = service.readAll();
		if(readAll != null)
		for(User user:readAll){
			System.out.println("email from db: "+user.getEmail());
		}
		return "create";
	}
	
	@RequestMapping(value="/get")
	public @ResponseBody User get(@RequestBody User user){
		return service.read(user);
	}
	
	/*@RequestMapping(value="/create", method=RequestMethod.POST)
	public @ResponseBody User create(
			@RequestParam String email,
			@RequestParam String password
			) {
 
		
		System.out.println("here1"+email);
		System.out.println(password);
		
		User newUser = new User();
		newUser.setEmail(email);
		newUser.setPassword(password);
		
		
		return service.create(newUser);
	}*/
	
	@RequestMapping(value="/update", method=RequestMethod.POST)
	public @ResponseBody User update(
			@RequestParam String email,
			@RequestParam String password,
			@RequestParam Integer role) {
 
		Role existingRole = new Role();
		existingRole.setRole(role);
		
		User existingUser = new User();
		existingUser.setEmail(email);
		existingUser.setPassword(password);
		existingUser.setRole(existingRole);
		
		return service.update(existingUser);
	}
	
	@RequestMapping(value="/delete", method=RequestMethod.POST)
	public @ResponseBody Boolean delete(
			@RequestParam String email) {
 
		User existingUser = new User();
		existingUser.setEmail(email);
		
		return service.delete(existingUser);
	}
}
